package com.hx.jvm.classloader.hotdeploy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author Minghua Chen
 * @since on 2020/8/17 12:52
 */
public class MyClassLoader extends ClassLoader {
    private static final String BASE_DIR = "D:/me/gitcode/testloader/";

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String fileName = name.replaceAll("\\.", "/");
        fileName = BASE_DIR + fileName + ".class";
        byte[] bytes = getBytes(fileName);
        assert bytes != null;
        return defineClass(name, bytes, 0, bytes.length);

    }


    /**
     * 读取字节码文件 获取字节码数组
     *
     * @return
     */
    private byte[] getBytes(String fileName) {
        File classFile = new File(fileName);
        if (classFile.exists()) {
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(classFile);
                out = new ByteArrayOutputStream();

                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = in.read(buff)) != -1) {
                    out.write(buff, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            assert out != null;
            return out.toByteArray();
        }
        return null;
    }
}
